package rensoft.android.view.requestdata;

import static rensoft.java.lang.Lang.is;

import rensoft.android.HasActivity;
import rensoft.android.HasActivityPresenter;
import rensoft.android.rpc.IServerRequest;
import rensoft.android.view.RequestPresenter;
import rensoft.java.event.Event.EventRegistration;
import rensoft.java.event.Listener;
import rensoft.java.lang.Callback;

public class SimpleDataPresenter<RequestType extends IServerRequest> extends HasActivityPresenter
    implements DataPresenter<RequestType> {

  private IRequestData<RequestType> data;
  private final RequestPresenter<RequestType> requestPresenter;
  private Callback<RequestType> loadListener;

  public SimpleDataPresenter(HasActivity hasActivity, String id, int loadingIndicatorId) {
    super(hasActivity);
    requestPresenter = new RequestPresenter<RequestType>(this, id, loadingIndicatorId);
  }

  @Deprecated
  public SimpleDataPresenter(HasActivity hasActivity, String id, IRequestData<RequestType> data,
      int loadingIndicatorId) {
    super(hasActivity);
    this.data = data;
    requestPresenter = new RequestPresenter<RequestType>(this, id, loadingIndicatorId);
  };

  public IRequestData<RequestType> getData() {
    return data;
  }

  public void load() {
    data.load();
    requestPresenter.setRequest(data.getDataRequest());
  }

  public void reload() {
    data.reload();
    requestPresenter.setRequest(data.getDataRequest());
  }

  public void setCreateRequestListener(final Callback<RequestType> callback) {
    data.setCreateRequestListener(new Callback<RequestType>() {
      @Override
      public void onCall(RequestType value) {
        callback.onCall(value);
      }
    });
  }

  public void setData(IRequestData<RequestType> data) {
    this.data = data;
  }

  public void setFailedListener(Callback<RequestType> callback) {
    requestPresenter.setFailedListener(callback);
  }

  public void setLoadListener(Callback<RequestType> loadListener) {
    this.loadListener = loadListener;
  }

  @Override
  protected void onCreate() {
    super.onCreate();
    listen(data.eventLoaded(), new Listener<RequestType>() {
      public void onEvent(EventRegistration registration, RequestType data) {
        if (!isPaused()) onDataLoaded(data);
      }
    });
  }

  protected void onDataLoaded(RequestType data) {
    if (is(loadListener)) loadListener.onCall(data);
  }
}
